import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:file_picker/file_picker.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'openvpn_service.dart';

class VPNScreen extends StatefulWidget {
  const VPNScreen({super.key});

  @override
  State<VPNScreen> createState() => _VPNScreenState();
}

class _VPNScreenState extends State<VPNScreen> {
  final OpenVPNService vpnService = OpenVPNService();
  String? ovpnFilePath;
  String? keyFilePath;
  String connectionStatus = '未连接';
  String log = '';
  bool isLoading = false;
  final Logger logger = Logger();

  @override
  void initState() {
    super.initState();
    initializeVPNService();
    loadSavedConfig();
  }

  Future<void> initializeVPNService() async {
    try {
      await vpnService.init(
        onVPNStatusChanged: (status) {
          setState(() {
            connectionStatus = status;
            addLog('状态更新: $status');
          });
        },
        onConnectionStatusChanged: (status) {
          setState(() {
            addLog(
              '连接详情 - 持续时间: ${status.duration}, 接收: ${status.byteIn}, 发送: ${status.byteOut}',
            );
          });
        },
      );
      addLog('VPN 服务初始化成功');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('VPN 服务初始化成功')));
      }
    } catch (e, stackTrace) {
      addLog('VPN 服务初始化失败: $e\n堆栈跟踪: $stackTrace');
      logger.e('VPN 服务初始化失败: $e\n堆栈跟踪: $stackTrace');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('VPN 服务初始化失败: $e')));
      }
    }
  }

  Future<void> loadSavedConfig() async {
    final prefs = await SharedPreferences.getInstance();
    final ovpnContent = prefs.getString('ovpn_content');
    final keyContent = prefs.getString('key_content');
    if (ovpnContent != null && keyContent != null) {
      setState(() {
        ovpnFilePath = '已保存的 ovpn 文件';
        keyFilePath = '已保存的 key 文件';
        addLog('已加载保存的配置文件');
      });
    }
  }

  Future<void> saveConfig(String ovpnContent, String keyContent) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('ovpn_content', ovpnContent);
    await prefs.setString('key_content', keyContent);
    addLog('配置文件已保存');
  }

  Future<void> deleteConfig() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('ovpn_content');
    await prefs.remove('key_content');
    setState(() {
      ovpnFilePath = null;
      keyFilePath = null;
      addLog('配置文件已删除');
    });
    if (mounted) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('配置文件已删除')));
    }
  }

  void addLog(String message) {
    final timestamp = DateTime.now().toString();
    log = '[$timestamp] $message\n$log';
  }

  Future<void> pickOvpnFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['ovpn', 'bin'],
      );
      if (result != null && result.files.single.path != null) {
        final ovpnContent = await File(
          result.files.single.path!,
        ).readAsString();
        setState(() {
          ovpnFilePath = result.files.single.path;
          addLog('已选择 ovpn 文件: ${ovpnFilePath!.split('/').last}');
        });
        if (keyFilePath != null) {
          await saveConfig(
            ovpnContent,
            await File(keyFilePath!).readAsString(),
          );
        }
      }
    } catch (e) {
      addLog('选择 ovpn 文件失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('选择 ovpn 文件失败: $e')));
      }
    }
  }

  Future<void> pickKeyFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['key'],
      );
      if (result != null && result.files.single.path != null) {
        final keyContent = await File(result.files.single.path!).readAsString();
        setState(() {
          keyFilePath = result.files.single.path;
          addLog('已选择 key 文件: ${keyFilePath!.split('/').last}');
        });
        if (ovpnFilePath != null) {
          await saveConfig(
            await File(ovpnFilePath!).readAsString(),
            keyContent,
          );
        }
      }
    } catch (e) {
      addLog('选择 key 文件失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('选择 key 文件失败: $e')));
      }
    }
  }

  Future<void> connectVPN({bool isManual = true}) async {
    final prefs = await SharedPreferences.getInstance();
    final ovpnContent = prefs.getString('ovpn_content');
    final keyContent = prefs.getString('key_content');

    if (ovpnContent == null || keyContent == null) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('登录超时，请重新选择配置文件')));
      }
      return;
    }

    setState(() {
      isLoading = true;
    });

    logger.i('VPN 连接已启动 (isManual=$isManual)');
    vpnService.connect(ovpnContent, keyContent); // 异步启动连接，不等待结果
    if (isManual) {
      await prefs.setBool('vpn_connected_once', true); // 仅手动连接设置标志
      logger.i('设置 vpn_connected_once=true');
    }
    if (mounted) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('VPN 连接已启动')));
      Navigator.pop(context);
      Future.delayed(const Duration(milliseconds: 500), () {
        if (mounted) {
          Navigator.pushNamed(context, '/vpn');
        }
      });
    }

    setState(() {
      isLoading = false;
    });
  }

  Future<void> disconnectVPN() async {
    setState(() {
      isLoading = true;
    });

    try {
      await vpnService.disconnect();
      await Future.delayed(const Duration(milliseconds: 500));
      setState(() {
        connectionStatus = 'DISCONNECTED';
      });
      if (mounted) {
        Navigator.pushReplacementNamed(context, '/vpn');
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('VPN 已断开')));
      }
    } catch (e, stackTrace) {
      addLog('VPN 断开失败: $e\n堆栈跟踪: $stackTrace');
      logger.e('VPN 断开失败: $e\n堆栈跟踪: $stackTrace');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('VPN 断开失败: $e')));
      }
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  void copyLog() {
    Clipboard.setData(ClipboardData(text: log));
    if (mounted) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('日志已复制到剪贴板')));
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('VPN 连接'),
        actions: [
          IconButton(
            icon: const Icon(Icons.copy),
            onPressed: copyLog,
            tooltip: '复制日志',
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '连接状态: $connectionStatus',
              style: const TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: pickOvpnFile,
              child: Text(
                ovpnFilePath == null
                    ? '选择 ovpn 文件'
                    : '已选择: ${ovpnFilePath!.split('/').last}',
              ),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: pickKeyFile,
              child: Text(
                keyFilePath == null
                    ? '选择 ta.key 文件'
                    : '已选择: ${keyFilePath!.split('/').last}',
              ),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: deleteConfig,
              child: const Text('删除配置文件'),
            ),
            const SizedBox(height: 16),
            isLoading
                ? const Center(child: CircularProgressIndicator())
                : Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          onPressed: connectionStatus == 'CONNECTED'
                              ? null
                              : () => connectVPN(isManual: true),
                          child: const Text('连接 VPN'),
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: ElevatedButton(
                          onPressed: connectionStatus == 'DISCONNECTED'
                              ? null
                              : disconnectVPN,
                          child: const Text('断开 VPN'),
                        ),
                      ),
                    ],
                  ),
          ],
        ),
      ),
    );
  }
}
